package com.ruicar.afs.cloud.seats.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.security.dto.UserInfo;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.security.vo.UserVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.seats.condition.*;
import com.ruicar.afs.cloud.seats.entity.*;
import com.ruicar.afs.cloud.seats.feign.UserDetailsInfoFeign;
import com.ruicar.afs.cloud.seats.service.*;
import com.ruicar.afs.cloud.seats.util.JobTag;
import com.ruicar.afs.cloud.seats.util.PostStatus;
import com.ruicar.afs.cloud.seats.util.WorkflowTypeUtil;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FLowNodeUserBean;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FlowNodeBean;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tiankai
 * @Describe 操作组管理功能集
 * Created on 2020-05-15
 */
@Slf4j
@RestController
@RequestMapping("/group")
@AllArgsConstructor
@Api(description = "操作组管理接口")
public class GroupManageController {

    @Autowired
    private GroupUserService userService;
    @Autowired
    private PersonalPowerParamService paramService;
    @Autowired
    private UserCollocationService userCollocationService;
    @Autowired
    private PostChangeLogService logService;
    @Autowired
    private WorkflowService workflowService;
    @Autowired
    private GroupSceneService sceneService;


    @GetMapping(value = {"/getGroupInfo"})
    @ApiOperation(value = "获取操作组信息（分页）")
    public IResponse<Boolean> getGroupInfo(@ModelAttribute ReleaseGroupCondition condition) {
        List<ReleaseGroupCondition> MemberArticleBeans = new ArrayList();
        WorkFlowResponse<List<FlowNodeBean>> workFlowResponse = workflowService.queryAllNode();
        String deptId = this.getDeptId();
        List<FlowNodeBean> list = workFlowResponse.getAfsData();
        for (FlowNodeBean flowNodeBean : list) {
            ReleaseGroupCondition groupCondition = new ReleaseGroupCondition();
            groupCondition.setName(flowNodeBean.getName());
            groupCondition.setId(flowNodeBean.getId());
            groupCondition.setServiceId(flowNodeBean.getServiceId());
            groupCondition.setAfsFlowKey(flowNodeBean.getAfsFlowKey());
            groupCondition.setAfsFlowKeyName(WorkflowTypeUtil.getApproveTypeName(flowNodeBean.getAfsFlowKey()));
            GroupScene groupScene = sceneService.getOne(Wrappers.<GroupScene>query().lambda().eq(GroupScene::getProcessId,flowNodeBean.getServiceId()));
            if (ObjectUtil.isNotNull(groupScene)&&String.valueOf(groupScene.getDeptId()).equals(deptId)) {
                MemberArticleBeans.add(groupCondition);
            }
        }
        if (condition.getGroupName() != null && !condition.getGroupName().isEmpty()) {
            MemberArticleBeans = MemberArticleBeans.stream().filter(d ->
            {
                if ( d.getName().contains(condition.getGroupName())) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
        }
        List<ReleaseGroupCondition> MemberArticleBeanPage = new ArrayList();
        int currIdx = (condition.getPageNumber() > 1 ? (condition.getPageNumber() - 1) * condition.getPageSize() : 0);
        for (int i = 0; i < condition.getPageSize() && i < MemberArticleBeans.size() - currIdx; i++) {
            ReleaseGroupCondition memberArticleBean = MemberArticleBeans.get(currIdx + i);
            MemberArticleBeanPage.add(memberArticleBean);
        }
        IPageCondition iPageCondition = new IPageCondition();
        iPageCondition.setRecords(MemberArticleBeanPage);
        iPageCondition.setTotal(MemberArticleBeans.size());
        return IResponse.success(iPageCondition);
    }

    @GetMapping(value = {"/queryMemberList"})
    @ApiOperation(value = "获取成员信息（分页）")
    public IResponse<Boolean> queryMemberList(@ModelAttribute ReleaseGroupCondition condition) {
        List<GroupUserCondition> groupUserConditionList = new ArrayList<>();
        List<GroupUserCondition> MemberArticleBeanPage = new ArrayList();
        WorkFlowResponse<Page<FLowNodeUserBean>> workFlowResponse = workflowService.queryNodeUser(condition.getGroupId(), 1, 10000);
        List<FLowNodeUserBean> list = workFlowResponse.getAfsData().getRecords();
        for (FLowNodeUserBean fLowNodeUserBean : list) {
            GroupUserCondition userCondition = new GroupUserCondition();
            userCondition.setProcedureId(fLowNodeUserBean.getId());
            userCondition.setLoginName(fLowNodeUserBean.getUserName());
            userCondition.setUserName(fLowNodeUserBean.getUserRealName());
            userCondition.setWeight(fLowNodeUserBean.getWeight());
            userCondition.setGroupId(condition.getGroupId());
            userCondition.setGroupName(condition.getGroupName());
            userCondition.setAgencyNumber(fLowNodeUserBean.getTaskCount());
            GroupUser user = userService.getOne(Wrappers.<GroupUser>query().lambda().eq(GroupUser::getLoginName, fLowNodeUserBean.getUserName()).eq(GroupUser::getGroupId, condition.getGroupId()));
            if (ObjectUtil.isNotNull(user)) {
                userCondition.setWeight(user.getWeight());
                userCondition.setGrabWeight(user.getGrabWeight());
                userCondition.setWeightUpper(user.getWeightUpper());
                if(!user.getProcedureId().equals(fLowNodeUserBean.getId())){
                    user.setProcedureId(fLowNodeUserBean.getId());
                    userService.saveOrUpdate(user);
                }
            } else {
                user = new GroupUser();
                user.setGroupId(condition.getGroupId());
                user.setLoginName(fLowNodeUserBean.getUserName());
                user.setWeight(fLowNodeUserBean.getWeight());
                user.setProcedureId(fLowNodeUserBean.getId());
                userService.saveOrUpdate(user);
            }
            UserCollocation userCollocation = userCollocationService.getOne(Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getLoginName, fLowNodeUserBean.getUserName()));
            if (ObjectUtil.isNotNull(userCollocation)) {
                userCondition.setPostStatus(userCollocation.getPostStatus());
                userCondition.setTotalWeight(userCollocation.getTotalWeight());
                userCondition.setAgentId(userCollocation.getAgentId());
                userCondition.setAgent(userCollocation.getAgent());
                userCondition.setAgentGroupLeaderId(userCollocation.getAgentGroupLeaderId());
                userCondition.setAgentGroupLeader(userCollocation.getAgentGroupLeader());
                userCondition.setGroupLeaderId(userCollocation.getGroupLeaderId());
                userCondition.setGroupLeader(userCollocation.getGroupLeader());
            } else {
                userCondition.setPostStatus("");
            }
            groupUserConditionList.add(userCondition);
        }
        IPageCondition iPageCondition = new IPageCondition();
        if (condition.getUserName() != null && !condition.getUserName().isEmpty()) {
            groupUserConditionList = groupUserConditionList.stream().filter(d ->
            {
                if (!StringUtils.isEmpty(d.getUserName()) && d.getUserName().contains(condition.getUserName())) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
        }
        if (condition.getLoginName() != null && !condition.getLoginName().isEmpty()) {
            groupUserConditionList = groupUserConditionList.stream().filter(d -> d.getLoginName().contains(condition.getLoginName())).collect(Collectors.toList());
        }
        int currIdx = (condition.getPageNumber() > 1 ? (condition.getPageNumber() - 1) * condition.getPageSize() : 0);
        for (int i = 0; i < condition.getPageSize() && i < groupUserConditionList.size() - currIdx; i++) {
            GroupUserCondition groupUserCondition = groupUserConditionList.get(currIdx + i);
            MemberArticleBeanPage.add(groupUserCondition);
        }
        iPageCondition.setRecords(groupUserConditionList);
        iPageCondition.setTotal(groupUserConditionList.size());
        return IResponse.success(iPageCondition);
    }

    @RequestMapping(value = "/updateMember", method = RequestMethod.POST)
    @ApiOperation(value = "修改成员信息")
    public IResponse<Boolean> updateMember(@RequestBody GroupUserCondition userCondition) {
        List<String> gwtUserIds = new ArrayList<>();
        gwtUserIds.add(userCondition.getProcedureId());
        WorkFlowResponse workFlowResponse = workflowService.changeWeight(gwtUserIds, userCondition.getWeight());
        common(userCondition.getLoginName(), userCondition, workFlowResponse);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/batchUpdateMember/{ids}", method = RequestMethod.POST)
    @ApiOperation(value = "批量修改成员信息")
    public IResponse<Boolean> batchUpdateMember(@PathVariable String[] ids, @RequestBody GroupUserCondition userCondition) {
        for (String id : ids) {
            String loginName = id;
            GroupUser user = userService.getOne(Wrappers.<GroupUser>query().lambda().eq(GroupUser::getLoginName, id).eq(GroupUser::getGroupId, userCondition.getGroupId()));
            List<String> gwtUserIds = new ArrayList<>();
            gwtUserIds.add(user.getProcedureId());
            WorkFlowResponse workFlowResponse = workflowService.changeWeight(gwtUserIds, userCondition.getWeight());
            common(loginName, userCondition, workFlowResponse);
        }
        return new IResponse().setData(true);
    }

    /**
     * @Describe 成员信息更新
     * Created on 2020-05-15
     * @author tiankai
     */
    public void common(String id, GroupUserCondition userCondition, WorkFlowResponse workFlowResponse) {
        GroupUser user = userService.getOne(Wrappers.<GroupUser>query().lambda().eq(GroupUser::getLoginName, id).eq(GroupUser::getGroupId, userCondition.getGroupId()));
        if (workFlowResponse.getSuccess() == 1 && ObjectUtil.isNotNull(workFlowResponse)) {
            user.setWeight(userCondition.getWeight());
        }
        user.setGrabWeight(userCondition.getGrabWeight());
        user.setWeightUpper(userCondition.getWeightUpper());
        UserCollocation userCollocation = userCollocationService.getOne(Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getLoginName, id));
        if (ObjectUtil.isNotNull(userCollocation)) {
            userCollocation = this.updateTotalWeight(userCondition, userCollocation);
        } else {
            userCollocation = new UserCollocation();
            userCollocation.setLoginName(id);
            userCollocation = this.updateTotalWeight(userCondition, userCollocation);
        }
        userCollocationService.saveOrUpdate(userCollocation);
        userService.saveOrUpdate(user);
    }

    /**
     * @Describe 更改总权重
     * Created on 2020-05-15
     * @author tiankai
     */
    public UserCollocation updateTotalWeight(GroupUserCondition userCondition, UserCollocation userCollocation) {
        if (userCondition.getTotalWeight() != null) {
            WorkFlowResponse workFlowResponse = workflowService.changeTotalWeight(userCollocation.getLoginName(), userCondition.getTotalWeight().intValue());
            if (workFlowResponse.getSuccess() == 1 && ObjectUtil.isNotNull(workFlowResponse)) {
                userCollocation.setTotalWeight(userCondition.getTotalWeight());
            }
        }
        userCollocation.setUserRealName(userCondition.getUserName());
        return userCollocation;
    }

    @RequestMapping(value = "/deleteMember", method = RequestMethod.POST)
    @ApiOperation(value = "删除成员信息")
    public IResponse<Boolean> deleteMember(@RequestBody GroupUser groupUser) {
        GroupUser user = userService.getOne(Wrappers.<GroupUser>query().lambda().eq(GroupUser::getLoginName, groupUser.getLoginName()).eq(GroupUser::getGroupId, groupUser.getGroupId()));
        List<String> gwtUserIds = new ArrayList<>();
        gwtUserIds.add(user.getProcedureId());
        WorkFlowResponse workFlowResponse = workflowService.removeNodeUsers(gwtUserIds);
        if (workFlowResponse.getSuccess() == 1 && ObjectUtil.isNotNull(workFlowResponse)) {
            userService.removeById(user.getId());
        } else {
            return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("删除成员失败,错误信息:" + workFlowResponse.getMessage());
        }
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/addMember", method = RequestMethod.POST)
    @ApiOperation(value = "增加成员信息")
    public IResponse<Boolean> addMember(@RequestBody GroupUserCondition condition) {
        List<SysUserDto> users = condition.getSysUserDtoList();
        for (SysUserDto sysUserDto : users) {
            List<UserVo> userList = new ArrayList<>();
            UserVo userVo = new UserVo();
            userVo.setUsername(sysUserDto.getUsername());
            userVo.setUserRealName(sysUserDto.getUserRealName());
            userList.add(userVo);
            workflowService.addNodeUser(condition.getGroupId(), userList);
        }
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/updatePost", method = RequestMethod.POST)
    @ApiOperation(value = "编辑上岗/下岗状态")
    public IResponse<Boolean> updatePost(@RequestBody GroupUserCondition groupUserCondition) {
        List<GroupUserCondition> list = groupUserCondition.getList();
        for (GroupUserCondition userCondition : list) {
            UserCollocation userCollocation = userCollocationService.getOne((Wrappers.<UserCollocation>query().lambda().eq(UserCollocation::getLoginName, userCondition.getLoginName())));
            if (ObjectUtil.isNotNull(userCollocation)) {
                if (PostStatus.NO.getCode().equals(userCollocation.getPostStatus()) || "".equals(userCollocation.getPostStatus())) {
                    userCollocation.setPostStatus(PostStatus.YES.getCode());
                } else {
                    userCollocation.setPostStatus(PostStatus.NO.getCode());
                }
            } else {
                userCollocation = new UserCollocation();
                userCollocation.setPostStatus(PostStatus.YES.getCode());
                userCollocation.setLoginName(userCondition.getLoginName());
            }
            userCollocation.setJobTag(JobTag.NO.getCode());
            PostChangeLog postChangeLog = new PostChangeLog();
            postChangeLog.setLoginName(userCondition.getLoginName());
            postChangeLog.setUserName(userCondition.getUserName());
            postChangeLog.setPostChangeStatus(userCollocation.getPostStatus());
            postChangeLog.setChangeRemarks(groupUserCondition.getChangeRemarks());
            logService.saveOrUpdate(postChangeLog);
            userCollocationService.saveOrUpdate(userCollocation);
        }
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/powerUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "编辑个人权限参数")
    public IResponse<Boolean> powerUpdate(@RequestBody GroupUserCondition condition) {
        JSONObject jsonObject = condition.getParam();
        String[] strArray = {"calendar", "post", "duties", "top", "locking", "case", "procedure", "pag", "image", "query"};
        for (String string : strArray) {
            PersonalPowerParam param = new PersonalPowerParam();
            param.setParamName(string);
            param.setGroupId(condition.getGroupId());
            param.setLoginName(condition.getLoginName());
            if (!StringUtil.isEmpty((String) jsonObject.get(string))) {
                PersonalPowerParam powerParam = paramService.getOne(Wrappers.<PersonalPowerParam>query().lambda().eq(PersonalPowerParam::getLoginName, condition.getLoginName()).eq(PersonalPowerParam::getParamName, string), true);
                if (powerParam == null) {
                    param.setParamValue((String) jsonObject.get(string));
                    paramService.saveOrUpdate(param);
                } else {
                    powerParam.setParamValue((String) jsonObject.get(string));
                    paramService.saveOrUpdate(powerParam);
                }
            }
        }
        return new IResponse().setData(true);
    }

    @GetMapping(value = {"/queryPower"})
    @ApiOperation(value = "查看个人权限参数")
    public IResponse<GroupUserCondition> queryPower(@ModelAttribute GroupUser user) {
        GroupUserCondition userCondition = new GroupUserCondition();
        JSONObject jsonObject = new JSONObject();
        List<PersonalPowerParam> list = paramService.list(Wrappers.<PersonalPowerParam>query().lambda().eq(PersonalPowerParam::getGroupId, user.getGroupId()).eq(PersonalPowerParam::getLoginName, user.getLoginName()));
        if (list != null && !list.isEmpty()) {
            for (PersonalPowerParam param : list) {
                jsonObject.put(param.getParamName(), param.getParamValue());
            }
        }
        userCondition.setParam(jsonObject);
        return IResponse.success(userCondition);
    }

    @RequestMapping(value = "/groupTransfer", method = RequestMethod.POST)
    @ApiOperation(value = "转组")
    public IResponse<Boolean> groupTransfer(@RequestBody GroupUserCondition condition) {
        List<GroupUserCondition> list = condition.getList();
        for (GroupUserCondition user : list) {
            workflowService.moveUserToNode(user.getProcedureId(), user.getGroupId(), condition.getGroupId());
        }
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/agencyTask", method = RequestMethod.POST)
    @ApiOperation(value = "代办任务释放")
    public IResponse<Boolean> agencyTask(@RequestBody List<GroupUserCondition> list) {
        for (GroupUserCondition userCondition : list) {
            List<String> gwtUserIds = new ArrayList<>();
            gwtUserIds.add(userCondition.getProcedureId());
            workflowService.clearTaskCount(gwtUserIds);
        }
        return new IResponse().setData(true);
    }

    /**
     * @Describe 获取当前登录人
     * Created on 2020-07-29
     */
    public String getDeptId(){
//        IResponse IResponse = feign.info(SecurityUtils.getUsername());
//        String str3 = JSON.toJSONString(IResponse.getData());
//        JSONObject jsonObject = (JSONObject) JSONObject.parse(str3);
//        UserInfo userInfo = JSONObject.toJavaObject(jsonObject,UserInfo.class);
        return SecurityUtils.getUser().getDeptId()+"";
    }
}
